package org.jeecg.modules.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.entity.DbDelivery;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class CheckHeaderAspect {
    @Value("${Authorization}")
    private String AUTHORIZATION;
    @Pointcut("execution(* org.jeecg.modules.controller.aiservice.*.*(..)) && @annotation(org.jeecg.modules.annotation.CheckHeader)")
    public void checkHeaderPointcut(){}

    @Before("checkHeaderPointcut()")
    public void checkHeader(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request = null;

        // 遍历参数，找到HttpServletRequest对象
        for (Object arg : args) {
            if (arg instanceof HttpServletRequest) {
                request = (HttpServletRequest) arg;
                break;
            }
        }

        if (request != null) {
            // 获取请求头中的Auth字段
            String authHeader = request.getHeader("Authorization");
            if (authHeader == null || authHeader.isEmpty()) {
                throw new RuntimeException("缺少必要的Authorization请求头");
            } else if (!authHeader.equals(AUTHORIZATION)) {
                throw new RuntimeException("Authorization请求头错误");
            }
        }
    }
}

